<?php
namespace common\components\services\msg;

use common\components\helpers\Fun;
use common\components\helpers\MsgeventData;
use common\models\datas\MsgTemplate;
use yii\base\Action;
use yii\base\BaseObject;
use yii\base\Event;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\queue\JobInterface;
use yii\queue\sync\Queue;

class SendmsgJob extends BaseObject implements JobInterface {
    public $eventKey;
    public $ownerArray;
    public $db;//分店id
    public $site_id;
    public $admin_id;

    public function execute($queue){

        if(empty($this->eventKey)){
            return;
        }
        $templatearr = $this->getMsgtemplate();

        if($templatearr['single']){
            foreach ($templatearr['single'] as $tpl){
                $this->msgtemplateSend($tpl);
            }
        }
        /*
         * 1. 先将所有的日志信息放到数组列表里面，然后执行批量插入操作，获取批量插入的所有id；
         * 2. 将id放到列表中，然后循环调用shell进行消息发送

        $tmpdir = dirname(dirname(dirname(dirname(__DIR__)))) . "/console/runtime/logs/message.log";
        if (($fp = @fopen($tmpdir, 'a')) === false) {
            shell_exec("chmod 0777 $tmpdir");
        }*/
        /*
         * 1. 批量插入到数据库，将所有的符合要求的信息插入到数据库
         * 2. 然后批量对msg_log进行批量检测的发送；
         */
        if ($templatearr['group']){
            foreach ($templatearr['group'] as $tpl){
                $this->msgtemplateSend($tpl);
            }
        }
    }

    public function getMsgtemplate(){
        $tpl_arr = (new MsgeventData())->getTemplatebyKey($this->eventKey);
        $result_arr = $result_group = $result_single = [];
        if($tpl_arr != '不存在' && count($tpl_arr) > 0){
            foreach ($tpl_arr as $k=>$v){
                if($k !== 'group'){
                    //k是模板code，v是接收的对象信息
                    $mt = MsgTemplate::findOne(['msg_template_code'=>$k]);
                    if($mt){
                        $result['template'] = $mt;
                        $result['receive_group'] = $v;
                        $result_single[] = $result;
                    }else{
                        \Yii::error('msg template is empty');
                    }
                }else{
                    foreach ($v as $h=>$group_item){
                        $mtt = MsgTemplate::findOne(['msg_template_code'=>$h]);
                        if($mtt){
                            $result['template'] = $mtt;
                            $result['receive_group'] = $group_item;
                            $result_group[] = $result;
                        }
                    }
                }
            }
            $result_arr['single'] = $result_single;
            $result_arr['group'] = $result_group;
        }
        return $result_arr;
    }

    private function msgtemplateSend($tpl){
        if($tpl == null){
            return;
        }
        $filedir = dirname(dirname(dirname(dirname(__DIR__))));
        //获取接收者信息
        $receive_name = $tpl['receive_group'];
        $receive_data = $this->getReceiveDetail($receive_name);
        $result_arr = $receive_data['result_arr'];
        $mobile_key = isset($receive_data['mobile_key'])?$receive_data['mobile_key']:null;
        $email_key = isset($receive_data['email_key'])?$receive_data['email_key']:null;
        $receive_name = isset($receive_data['receive_name'])?$receive_data['receive_name']:null;
        $key_related_value = isset($receive_data['key_related_value'])?$receive_data['key_related_value']:null;
        $template = $tpl['template'];
        if(!empty($result_arr)){
            $msgs_arr = $this->exeTemplateArray($template,$receive_name,$result_arr,$mobile_key,$email_key,$key_related_value);
            if(!empty($msgs_arr) && count($msgs_arr)>0){
                    $trans = \Yii::$app->db->beginTransaction();
                    $maxid = (new Query())->from('{{%msg_log}}')->max('id');
                    $maxid = $maxid+1;
                    \Yii::$app->db->createCommand()->batchInsert('{{%msg_log}}',['site_id','admin_id','message_type_id','send_way','send_group','receiver_info','message_name','message_text','created_at'],$msgs_arr)->execute();
                    $maxid2 = (new Query())->from('{{%msg_log}}')->max('id');
                    $trans->commit();
                $query = (new Query())->from('{{%msg_log}}')->where(['between','id',$maxid,$maxid2]);
                $query_ser = base64_encode(gzcompress(serialize($query)));
                $server_name = \Yii::$app->params['swooleTaskName'];
                if($server_name == "dmdswoole_test"){
                    shell_exec("cd $filedir && nohup $filedir/yii_test msg/sendclassmanage $query_ser >/dev/null 2>&1 &");
                }else{
                    shell_exec("cd $filedir && nohup $filedir/yii msg/sendclassmanage $query_ser >/dev/null 2>&1 &");
                }

            }
        }
    }

    /**
     * @param $receive_name
     * @return null
     * 一对一，只不过中间关联表跨库跨表多种情况
     */
    public function getReceiveDetail($receive_name)
    {
        $receive_arr = explode('->',$receive_name);
        $result = null;
        $isbranch_preg = '/^zhtfrontend*/i';
        $key_related_value = '';
        $mobile_key = $email_key = $old_model_primarykey = null;
        if(!empty($receive_arr)){
            foreach ($receive_arr as $k=>$v){
                if($k == 0){
                    $first_arr = explode(':',$v);
                    if(count($first_arr) == 1){//一对一的情况
                        $first_group = (new MsgeventData())->getReceiveGroupByKey($first_arr[0]);
                        $first_model = isset($first_group['model']) ? $first_group['model'] : null;
                        $related_key = $first_group['key'];//用户在对应的模型中的外键字段名
                        /*
                         * 要区分是仅发送短信还是有模型对应
                         */
                        if(!empty($first_model)){
                            $mobile_key = isset($first_group['mobile_key'])&&!empty($first_group['mobile_key'])?$first_group['mobile_key']:null;
                            $email_key = isset($first_group['email_key'])&&!empty($first_group['email_key'])?$first_group['email_key']:null;
                            $key_related_value = ArrayHelper::keyExists($related_key, $this->ownerArray) ? $this->ownerArray[$related_key] : '';
                            $primary_key = isset($first_group['primary_key'])?$first_group['primary_key']:'id';
                            if(!empty($key_related_value)){
                                if(!empty($first_model)){
                                    //------------------------------待优化区分分店还是总店
                                    $table_name = $first_model::tableName();
                                    if(preg_match($isbranch_preg,$first_model)){
                                        $result = (new Query())->select('*')->from($table_name)->where([$primary_key=>$key_related_value])->all($this->db);
                                    }else{
                                        $result = (new Query())->select('*')->from($table_name)->where([$primary_key=>$key_related_value])->all();
                                    }
                                    $old_model_primarykey = isset($first_group['primary_key'])?$first_group['primary_key']:null;
                                }else{
                                    $result = null;
                                    break;
                                }
                            }else{
                                $result = null;
                                break;
                            }
                        }else{
                            $key_related_value = ArrayHelper::keyExists($related_key, $this->ownerArray) ? $this->ownerArray[$related_key] : '';
                            if(!empty($key_related_value)){
                                $result[] = 'ActionObject';
                                break;
                            }else{
                                $result = null;
                                break;
                            }
                        }

                    }elseif (count($first_arr) == 2){//一对多的情况
                        $first_group = (new MsgeventData())->getReceiveGroupByKey($first_arr[0]);
                        $event = (new MsgeventData())->getEventbyKey($this->eventKey);
                        $primary_key = isset($event['primary_key'])?$event['primary_key']:'id';
                        $first_model = isset($first_group['model']) ? $first_group['model'] : null;
                        if(!empty($first_model)){
                            $mobile_key = isset($first_group['mobile_key'])&&!empty($first_group['mobile_key'])?$first_group['mobile_key']:null;
                            $email_key = isset($first_group['email_key'])&&!empty($first_group['email_key'])?$first_group['email_key']:null;
                            $table_name = $first_model::tableName();
                            if(preg_match($isbranch_preg,$first_model)){
                                $result = (new Query())->select('*')->from($table_name)->where([$first_arr[1] => $this->ownerArray[$primary_key]]);
                                if(isset($first_group['conditions']) && !empty($first_group['conditions'])){
                                    $result = $result->andWhere($first_group['conditions']);
                                }
                                $result = $result->all($this->db);
                            }else{
                                $result = (new Query())->select('*')->from($table_name)->where([$first_arr[1] => $this->ownerArray[$primary_key]]);
                                if(isset($first_group['conditions']) && !empty($first_group['conditions'])){
                                    $result = $result->andWhere($first_group['conditions']);
                                }
                                $result = $result->all();
                            }
                            $old_model_primarykey = isset($first_group['primary_key'])?$first_group['primary_key']:null;
                        }else{
                            $result = null;
                            break;
                        }
                    }
                }else{
                    if(!empty($result)){
                        $v_arr = explode(':',$v);
                        if(count($v_arr) == 1){//一对一的情况考虑
                            $current_group = (new MsgeventData())->getReceiveGroupByKey($v);
                            $current_model = isset($current_group['model'])?$current_group['model']:null;
                            $current_key = $current_group['key'];
                            $mobile_key = isset($current_group['mobile_key'])&&!empty($current_group['mobile_key'])?$current_group['mobile_key']:null;
                            $email_key = isset($current_group['email_key'])&&!empty($current_group['email_key'])?$current_group['email_key']:null;
                            if(!empty($current_model)){
                                $passed_arr = [];
                                foreach($result as $mod){
                                    if(!empty($mod[$current_key])){
                                        $passed_arr[] = $mod[$current_key];
                                    }
                                }
                                $primary_key = isset($current_group['primary_key'])?$current_group['primary_key']:'id';
                                $table_name = $current_model::tableName();
                                if(preg_match($isbranch_preg,$current_model)){
                                    $result = (new Query())->select('*')->from($table_name)->where([$primary_key=>$passed_arr])->all($this->db);//先直接写id吧。。。后面有工夫了再加
                                }else{
                                    $result = (new Query())->select('*')->from($table_name)->where([$primary_key=>$passed_arr])->all();
                                }
                                $old_model_primarykey = isset($current_group['primary_key'])?$current_group['primary_key']:null;
                            }else{
                                $result = null;
                                break;
                            }
                        }elseif(count($v_arr) == 2){
                            $current_group = (new MsgeventData())->getReceiveGroupByKey($v_arr[0]);
                            $model = isset($current_group['model']) ? $current_group['model'] : null;
                            foreach($result as $mod){
                                if(!empty($mod[$old_model_primarykey])){
                                    $passed_arr[] = $mod[$old_model_primarykey];
                                }
                            }
                            if(!empty($model)){
                                $mobile_key = isset($current_group['mobile_key'])&&!empty($current_group['mobile_key'])?$current_group['mobile_key']:null;
                                $email_key = isset($current_group['email_key'])&&!empty($current_group['email_key'])?$current_group['email_key']:null;
                                $table_name = $model::tableName();
                                if(preg_match($isbranch_preg,$model)){
                                    $result = (new Query())->select('*')->from($table_name)->where([$v_arr[1] => $passed_arr]);
                                    if(isset($first_group['conditions']) && !empty($first_group['conditions'])){
                                        $result = $result->andWhere($first_group['conditions']);
                                    }
                                    $result = $result->all($this->db);
                                }else{
                                    $result = (new Query())->select('*')->from($table_name)->where([$v_arr[1] => $passed_arr]);
                                    if(isset($first_group['conditions']) && !empty($first_group['conditions'])){
                                        $result = $result->andWhere($first_group['conditions']);
                                    }
                                    $result = $result->all();
                                }
                                $old_model_primarykey = isset($current_group['primary_key'])?$current_group['primary_key']:null;
                            }else{
                                $result = null;
                                break;
                            }
                        }


                    }
                }
            }
            $data['key_related_value'] = $key_related_value;
            $data['result_arr'] = $result;//是数组
            $data['receive_name'] = $receive_name;
            $data['mobile_key'] = $mobile_key;
            $data['email_key'] = $email_key;
            return $data;
        }else{
            return null;
        }
    }

    public function getClassmanageMsgtemplate(){
        $tpl_arr = (new MsgeventData())->getTemplatebyKey($this->eventKey);
        $result_arr = $result_single = $result_group = [];
        if($tpl_arr != '不存在' && count($tpl_arr) > 0){
            foreach ($tpl_arr as $k=>$v){
                //k是模板code，v是接收的对象信息
                if($k !== 'group'){
                    $mt = MsgTemplate::findOne(['msg_template_code'=>$k]);
                    if($mt) {
                        $result['template'] = $mt;
                        $result['receive_group'] = $v;
                        $result_single[] = $result;
                    }else{
                        \Yii::error('msg template is empty');
                    }
                }else{
                    foreach ($v as $h=>$group_item){
                        $mtt = MsgTemplate::findOne(['msg_template_code'=>$h]);
                        if($mtt){
                            $result['template'] = $mtt;
                            $result['receive_group'] = $group_item;
                            $result_group[] = $result;
                        }
                    }
                }
            }
            $result_arr['single'] = $result_single;
            $result_arr['group'] = $result_group;
        }
        return $result_arr;
    }

    /*
     * 群发肯定是一对多的，有:来进行关联
     */
    public function msgtemplateSendforgroup($tpl){
        if($tpl == null){
            return;
        }
        $isbranch_preg = '/^zhtfrontend*/i';
        //获取接收者信息
        $mobile_key = $email_key = null;
        $receive_name = $tpl['receive_group'];
        $receive_arr = explode('->',$receive_name);
        $result_arr = null;
        if(!empty($receive_arr) && count($receive_arr)>0){
            foreach ($receive_arr as $k=>$v){
                if($k == 0){
                    $first_arr = explode(':',$v);
                    if(count($first_arr)>0){
                        $first_group = (new MsgeventData())->getReceiveGroupByKey($first_arr[0]);
                        $event = (new MsgeventData())->getEventbyKey($this->eventKey);
                        $primary_key = $event['primary_key']?$event['primary_key']:'id';
                        $first_model = $first_group['model'];
                        //------------------------------待优化区分分店还是总店
                        $table_name = $first_model::tableName();
                        if(preg_match($isbranch_preg,$first_model)){
                            $result_arr = (new Query())->select('*')->from($table_name)->where([$first_arr[1] => $this->ownerArray[$primary_key]])->all($this->db);
                        }else{
                            $result_arr = (new Query())->select('*')->from($table_name)->where([$first_arr[1] => $this->ownerArray[$primary_key]])->all();
                        }
                    }else{
                        break;
                        return;
                    }
                }else{
                    if(!empty($result_arr)){
                        $current_group = (new MsgeventData())->getReceiveGroupByKey($v);
                        $current_model = $current_group['model'];
                        $current_key = $current_group['key'];
                        $mobile_key = isset($current_group['mobile_key'])&&!empty($current_group['mobile_key'])?$current_group['mobile_key']:null;
                        $email_key = isset($current_group['email_key'])&&!empty($current_group['email_key'])?$current_group['email_key']:null;
                        $passed_arr = [];
                        foreach($result_arr as $mod){
                            if(!empty($mod[$current_key])){
                                $passed_arr[] = $mod[$current_key];
                            }
                        }
                        //$table_name1 = $current_model::tableName();
                        //$result_arr = (new Query())->select('*')->from($table_name1)->where(['id'=>$passed_arr])->all($this->db);
                        //------------------------------待优化区分分店还是总店
                        $primary_key = isset($current_group['primary_key'])?$current_group['primary_key']:'id';
                        $table_name = $current_model::tableName();
                        if(preg_match($isbranch_preg,$current_model)){
                            $result_arr = (new Query())->select('*')->from($table_name)->where([$primary_key=>$passed_arr])->all($this->db);//先直接写id吧。。。后面有工夫了再加
                        }else{
                            $result_arr = (new Query())->select('*')->from($table_name)->where([$primary_key=>$passed_arr])->all();
                        }
                    }
                }
            }
        }
        $data = [];
        if(!empty($result_arr)){
            $data['result_arr'] = $result_arr;
            $data['receive_name'] = $receive_name;
            $data['mobile_key'] = $mobile_key;
            $data['email_key'] = $email_key;
        }
        return $data;
    }
    //获取短信模板
    private function getMessageTemplateSms($tpl){
        $str_sms = $tpl['sms_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_sms,'{$'.$k.'}')){
                $str_sms = str_replace('{$' . $k . '}', $v, $str_sms);
            }
        }
        return $str_sms;
    }
    //获取邮件模板
    private function getMessageTemplateMail($tpl){
        $str_email = $tpl['email_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_email,'{$'.$k.'}')){
                $str_email = str_replace('{$' . $k . '}', $v, $str_email);
            }
        }
        return $str_email;
    }

    //获取微信模板
    private function getMessageTemplateWechat($tpl){
        $str_wechat = $tpl['wechat_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_wechat,'{$'.$k.'}')){
                $str_wechat = str_replace('{$' . $k . '}', $v, $str_wechat);
            }
        }
        return $str_wechat;
    }

    //获取系统模板
    private function getMessageTemplatesSys($tpl){
        $str_sys = $tpl['sys_text'];
        foreach ($this->ownerArray as $k=>$v){
            if(strpos($str_sys,'{$'.$k.'}')){
                $str_sys = str_replace('{$' . $k . '}', $v, $str_sys);
            }
        }
        return $str_sys;
    }

    //进行批量插入的模板列表数据的生成
    public function exeTemplateArray($template=null,$receive_name=null,$result_arr=null,$mobile_key=null,$email_key=null,$key_related_value=null){
        if($template != null && $receive_name != null && $result_arr != null){
            if(count($result_arr) > 0){
                $is_sys = $is_sms = $is_email = $is_wechat = false;
                $tplsys = $tplsms = $tplemail = $tplwechat = $tplwechatname = null;
                if($template['sys_state'] == 1){
                    $is_sys = true;
                    $tplsys = $this->getMessageTemplatesSys($template);
                }
                if($template['sms_state'] == 1){
                    $is_sms = true;
                    $tplsms = $this->getMessageTemplateSms($template);
                }
                if($template['email_state'] == 1){
                    $is_email = true;
                    $tplemail = $this->getMessageTemplateMail($template);
                }
                if($template['wechat_state'] == 1){
                    $is_wechat = true;
                    //$tplwechatname=(new MsgeventData())->getNameByKey($this->eventKey);
                    $tplwechat = $this->getMessageTemplateWechat($template);
                }
                $result = [];
                $site_id = $this->site_id;
                $admin_id=$this->admin_id;
                foreach ($result_arr as $res){
                    if($is_sys){
                        $receive_info = null;
                        $receive_info = $res['id'];
                        $send_way = 'sys';
                        $msg = [];
                        $msg['site_id'] = $site_id;
                        $msg['admin_id'] = $admin_id;
                        $msg['message_type_id'] = $this->eventKey;
                        $msg['send_way'] = $send_way;
                        $msg['send_group'] = $receive_name;
                        $msg['receiver_info'] = $receive_info;
                        $msg['message_name'] = '';
                        $msg['message_text'] = $tplsys;
                        $msg['created_at'] = time();
                        $result[] = $msg;
                    }
                    if($is_sms == 1){//当短信发送模板开启
                        $receive_info = null;
                        if($res == 'ActionObject'){
                            $receive_info = $key_related_value;
                        }else{
                            $receive_info = isset($res[$mobile_key])?$res[$mobile_key]:null;
                        }
                        $send_way = 'sms';
                        $msg = [];
                        $msg['site_id'] = $site_id;
                        $msg['admin_id'] = $admin_id;
                        $msg['message_type_id'] = $this->eventKey;
                        $msg['send_way'] = $send_way;
                        $msg['send_group'] = $receive_name;
                        $msg['receiver_info'] = $receive_info;
                        $msg['message_name'] = '';
                        $msg['message_text'] = $tplsms;
                        $msg['created_at'] = time();
                        $result[] = $msg;
                    }

                    if($is_email == 1){
                        $receive_info = null;
                        $Messageemailname=(new MsgeventData())->getNameByKey($this->eventKey);
                        $receive_info = isset($res[$email_key])?$res[$email_key]:null;
                        $send_way = 'email';
                        $msg = [];
                        $msg['site_id'] = $site_id;
                        $msg['admin_id'] = $admin_id;
                        $msg['message_type_id'] = $this->eventKey;
                        $msg['send_way'] = $send_way;
                        $msg['send_group'] = $receive_name;
                        $msg['receiver_info'] = $receive_info;
                        $msg['message_name'] = $Messageemailname;
                        $msg['message_text'] = $tplemail;
                        $msg['created_at'] = time();
                        $result[] = $msg;
                    }

                    if($is_wechat == 1){//微信发送只针对用户，不针对无微信的教师机构，功能需求待定
                        $receive_info = null;
                        $Messagewechatname=(new MsgeventData())->getNameByKey($this->eventKey);
                        //还不确定存放opendid的表在哪里，暂时就按照login_auth来
                        $site = (new Query())->select('web_site_id')->from('{{%site}}')->where(['id'=>$this->site_id])->one();
                        $login_auth = (new Query())->from('{{%login_auth}}')->select('source_id')->where(['user_id'=>$res['id']])
                            ->andWhere(['web_site_id'=>$site['web_site_id']])->one();//根据关联的用户id值到loginauth中获取对应的openid
                        $receive_info = $login_auth['source_id'];
                        $send_way = 'wechat';
                        $msg = [];
                        $msg['site_id'] = $site_id;
                        $msg['admin_id'] = $admin_id;
                        $msg['message_type_id'] = $this->eventKey;
                        $msg['send_way'] = $send_way;
                        $msg['send_group'] = $receive_name;
                        $msg['receiver_info'] = $receive_info;
                        $msg['message_name'] = $Messagewechatname;
                        $msg['message_text'] = $tplwechat;
                        $msg['created_at'] = time();
                        $result[] = $msg;
                    }
                }
                return $result;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }
}